package cn.itcast.flink.process.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author lilulu
 */
public class StreamProcessStateTtlDemo {
    public static void main(String[] args) throws Exception {
        // 1. 执行环境-env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 数据源-source
        DataStreamSource<String> source = env.socketTextStream("node1", 9999);
        SingleOutputStreamOperator<String> processStream = source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> collector) throws Exception {
                String[] split = line.split("\\s+");
                for (String word : split) {
                    collector.collect(word);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String word) throws Exception {
                return Tuple2.of(word, 1);
            }
        }).keyBy(tuple -> tuple.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Integer>, String>() {
                    private ValueState<Integer> countState = null;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<Integer> stateDescriptor = new ValueStateDescriptor<>("countState", Integer.class);
                        //设置状态有效期
                        StateTtlConfig stateTtlConfig = StateTtlConfig
                                //状态存活的时间
                                .newBuilder(Time.seconds(5))
                                //什么时候更新状态中的值
                                .updateTtlOnCreateAndWrite()
                                //状态过期后，对程序可见性
                                .neverReturnExpired()
                                .build();
                        stateDescriptor.enableTimeToLive(stateTtlConfig);
                        this.countState = getRuntimeContext().getState(stateDescriptor);
                    }

                    @Override
                    public void processElement(Tuple2<String, Integer> tuple2, Context context, Collector<String> collector) throws Exception {
                        Integer historyValue = countState.value();
                        Integer currentValue = tuple2.f1;
                        if (historyValue == null) {
                            countState.update(currentValue);
                        } else {
                            countState.update(historyValue + currentValue);
                        }
                        String output = context.getCurrentKey() + " -> " + countState.value();
                        collector.collect(output);
                    }

                });
        // 3. 数据转换-transformation
        // 4. 数据终端-sink
        processStream.printToErr();
        // 5. 触发执行-execute
        env.execute("StreamProcessStateTtlDemo");
    }
}